package com.xiaoye.qbproject.util.poi;

import com.xiaoye.qbproject.vo.TroopsV2ImportVo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : ChenYao
 * @version : 1.0
 * @description :
 * @create : 2024-12-27 12:37
 */
public class TroopsV2ExcelUtil {
    public static void main(String[] args) {
        TroopsV2ExcelUtil excelUtil = new TroopsV2ExcelUtil();
        //读取excel数据
    /*    List<TroopsV2ImportVo> result = excelUtil.readExcelToObj("D:\\xy_文件\\开源QB系统说明_V2\\2025-01-13_整理数据\\部队_装备_战例数据整理_2025-01.xlsx");
        for (TroopsV2ImportVo map : result) {
            System.out.println(map);
        }*/
        Map<String, Object> map = excelUtil.readExcelMuchSheetToObj("D:\\xy_文件\\开源QB系统说明_V2\\2025-01-13_整理数据\\部队_装备_战例数据整理_2025-01.xlsx");
        System.out.println(map);
    }

    /**
     * 读取excel数据
     *
     * @param path
     */
    public List<TroopsV2ImportVo> readExcelToObj(String path) {

        Workbook wb = null;
        List<TroopsV2ImportVo> result = null;
        try {
            wb = WorkbookFactory.create(new File(path));
            result = readExcel(wb, 0, 1, 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param path
     * @description: 读取多个sheet
     * @author: ChenYao
     * @return: java.util.List<com.xiaoye.qbproject.vo.TroopsV2ImportVo>
     * @ceateDate: 2025-01-01 10:57
     */

    public Map<String, Object> readExcelMuchSheetToObj(String path) {

        Workbook wb = null;
        Map<String, Object> sheetMap = new HashMap<>();
        try {
            wb = WorkbookFactory.create(new File(path));
            // 打印每个工作表的名称
            int sheetCount = wb.getNumberOfSheets();
            List<TroopsV2ImportVo> result = new ArrayList<>();
            for (int i = 0; i < sheetCount; i++) {
                result = readExcel(wb, i, 1, 0);
                sheetMap.put(wb.getSheetName(i), result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sheetMap;
    }


    /**
     * 读取excel文件
     *
     * @param wb
     * @param sheetIndex    sheet页下标：从0开始
     * @param startReadLine 开始读取的行:从0开始
     * @param tailLine      去除最后读取的行
     */
    private List<TroopsV2ImportVo> readExcel(Workbook wb, int sheetIndex, int startReadLine, int tailLine) {
        Sheet sheet = wb.getSheetAt(sheetIndex);
        Row row = null;
        List<TroopsV2ImportVo> result = new ArrayList<TroopsV2ImportVo>();
        for (int i = startReadLine; i < sheet.getLastRowNum() - tailLine + 1; i++) {

            row = sheet.getRow(i);
            //TroopsV2ImportVo map = new HashMap<String, String>();
            TroopsV2ImportVo vo = new TroopsV2ImportVo();
            for (Cell c : row) {
                String returnStr = "";

                boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex());
                //判断是否具有合并单元格
                if (isMerge) {
                    String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
//                    System.out.print(rs + "------ ");
                    returnStr = rs;
                } else {
                    //设置单元格类型
                    c.setCellType(CellType.STRING);
//                    System.out.print(c.getRichStringCellValue()+"++++ ");
                    returnStr = c.getRichStringCellValue().getString();
                }
                if (c.getColumnIndex() == 0) {
                    vo.setParentName(returnStr);
                } else if (c.getColumnIndex() == 1) {
                    vo.setTroopsName(returnStr);
                } else if (c.getColumnIndex() == 2) {
                    vo.setTroopsNameEn(returnStr);
                } else if (c.getColumnIndex() == 3) {
                    vo.setAbbreviation(returnStr);
                } else if (c.getColumnIndex() == 4) {
                    vo.setSummary(returnStr);
                } else if (c.getColumnIndex() == 5) {
                    vo.setDomicile(returnStr);
                } else if (c.getColumnIndex() == 6) {
                    vo.setCountryName(returnStr);
                } else if (c.getColumnIndex() == 7) {
                    vo.setMilitaryService(returnStr);
                } else if (c.getColumnIndex() == 8) {
                    vo.setFormYear(returnStr);
                } else if (c.getColumnIndex() == 9) {
                    vo.setTakePartBattle(returnStr);
                } else if (c.getColumnIndex() == 10) {
                    vo.setZb(returnStr);
                }

            }
            result.add(vo);
//            System.out.println();

        }
        return result;

    }

    /**
     * 获取合并单元格的值
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    public String getMergedRegionValue(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();

        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();

            if (row >= firstRow && row <= lastRow) {

                if (column >= firstColumn && column <= lastColumn) {
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getCellValue(fCell);
                }
            }
        }

        return null;
    }

    /**
     * 判断合并了行
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    private boolean isMergedRow(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row == firstRow && row == lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断指定的单元格是否是合并单元格
     *
     * @param sheet
     * @param row    行下标
     * @param column 列下标
     * @return
     */
    private boolean isMergedRegion(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断sheet页中是否含有合并单元格
     *
     * @param sheet
     * @return
     */
    private boolean hasMerged(Sheet sheet) {
        return sheet.getNumMergedRegions() > 0;
    }

    /**
     * 合并单元格
     *
     * @param sheet
     * @param firstRow 开始行
     * @param lastRow  结束行
     * @param firstCol 开始列
     * @param lastCol  结束列
     */
    private void mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
    }

    /**
     * 获取单元格的值
     *
     * @param cell
     * @return
     */
    public String getCellValue(Cell cell) {

        if (cell == null) return "";

        if (cell.getCellType() == CellType.STRING) {

            return cell.getStringCellValue();

        } else if (cell.getCellType() == CellType.BOOLEAN) {

            return String.valueOf(cell.getBooleanCellValue());

        } else if (cell.getCellType() == CellType.FORMULA) {

            return cell.getCellFormula();

        } else if (cell.getCellType() == CellType.NUMERIC) {

            return String.valueOf(cell.getNumericCellValue());

        }
        return "";
    }
}
